//
//  MineViewController.swift
//  Exam-iOS
//
//  Created by 李胜锋 on 2018/1/29.
//  Copyright © 2018年 李胜锋. All rights reserved.
//

import UIKit
import StoreKit
import RxSwift
import RxCocoa
import AlamofireImage

class MineViewController: ViewController, UITableViewDelegate, UITableViewDataSource {
    
    static func controller() -> MineViewController {
        return MineViewController.viewController(storyboardName: "Mine") as! MineViewController
    }
    
    var pushControllerHandle:((_ vc:UIViewController, _ animate:Bool) -> Void)?

    @IBOutlet weak var loginBtn: UIButton!
    
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var avatarImageView: UIImageView!
    @IBOutlet weak var nickLabel: UILabel!
    var datasource = ["钱包", "使用指南", "修改考试级别",  "意见反馈",  "去评分",  "关于"]
    override func viewDidLoad() {
        super.viewDidLoad()
        
        
        avatarImageView.layer.cornerRadius = 74.0 / 2
        avatarImageView.clipsToBounds = true
        tableView.tableFooterView = UIView()

        
        
        var userTap = UITapGestureRecognizer.init(target: self, action: #selector(MineViewController.userTaped))
        nickLabel.isUserInteractionEnabled = true
        nickLabel.addGestureRecognizer(userTap)
        
        
        userTap = UITapGestureRecognizer.init(target: self, action: #selector(MineViewController.userTaped))
        avatarImageView.isUserInteractionEnabled = true
        avatarImageView.addGestureRecognizer(userTap)
        
        
        NotificationCenter.default.rx.notification(Notification.Name.init(rawValue: SideslipNotificationName.willOpen.rawValue)).subscribe(onNext: { [weak self] (notification) in
            ///更新UI
            self?.updateUI()
            ///更新用户信息
            self?.loadUserInfo()
            getStatusBar()?.backgroundColor = UIColor.clear
        }).disposed(by: disposeBag)
        
        
//        NotificationCenter.default.rx.notification(Notification.Name.init(rawValue: SideslipNotificationName.didClose.rawValue)).subscribe(onNext: { (notification) in
//            getStatusBar()?.backgroundColor = k_themeColor
//        }).disposed(by: disposeBag)
    }
    
    
    ///获取用户信息
    func loadUserInfo() {
        if AccountStorage.default.isLogin() == false {
            return
        }
        
        shurenProvider.rx.request(.userInfo).asObservable().mapRespnseToObject(type: AccountModel.self).subscribe(onNext: { [weak self] (account) in
            AccountStorage.default.updateAccount(account)

            ///更新UI
            self?.updateUI()
        }).disposed(by: disposeBag)
    }
    
    func updateUI() {
        
        let isLogin = AccountStorage.default.isLogin()
        
        if isLogin {
            nickLabel.text = AccountStorage.default.account.fullName
            
            guard let imageUrl = AccountStorage.default.account.profilePhoto else { return }
            if let url = URL.init(string: imageUrl) {
                avatarImageView.af_setImage(withURL: url, placeholderImage: UIImage.init(named: "default_avatar"))
            }
            loginBtn .setTitle("退出登录", for: .normal)
        }
        else {
            nickLabel.text = "请登录"
            avatarImageView.image = UIImage.init(named: "default_avatar")
            loginBtn .setTitle("登  录", for: .normal)
        }
        
    }
    
    @objc func userTaped() {
        let isLogin = AccountStorage.default.isLogin()
        if isLogin {
            let profileVC = ProfileViewController.controller()
            self.pushControllerHandle?(profileVC, true)
            sideslipCloseLeftMenu()
        }
        else {
            loginClick(loginBtn)
        }
    }
    
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return datasource.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)

        cell.textLabel?.text = datasource[indexPath.row]

        var left:CGFloat = 15.0
        if indexPath.row == datasource.count - 1 {
            left  = 0
        }
        cell.separatorInset = UIEdgeInsetsMake(0, left, 0, 0)
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        switch indexPath.row {
            
        case 0:
            //检查登录
            if login() == false { return }
            
            //钱包
            let coinVC = CoinViewController.controller()
            self.pushControllerHandle?(coinVC, true)
            
        case 1:
            //使用指南
            let softInstructionVC = SoftInstructionViewController()
            self.pushControllerHandle?(softInstructionVC, true)

        case 2:
            
            //检查登录
            if login() == false { return }
            
            //修改考试级别
            let levelVC = ExamLevelViewController.controller(.change)
            self.pushControllerHandle?(levelVC, true)
            
        case 3:
            //意见反馈
            let feedbackVC = FeedbackViewController()
            self.pushControllerHandle?(feedbackVC, true)
            
            
        case 4:
            //评分
            review()
            
        case 5:
            //关于我们
            let aboutusVC = AboutUsViewController.controller()
            self.pushControllerHandle?(aboutusVC, true)
        default:
            break
        }
        
        
        sideslipCloseLeftMenu()
    }
    
    func login() -> Bool {
        let isLogin = AccountStorage.default.isLogin()
        if isLogin == false {
            showLogin(controller: self, dismissHandle: { [weak self] (result) in
                self?.updateUI()
            })
        }
        
        return isLogin
    }
    
    @IBAction func loginClick(_ sender: UIButton) {
        
        let isLogin = AccountStorage.default.isLogin()
        if isLogin {
            //退出登录
            AccountService.logout(success: nil, failure: nil)
        }
        
        showLogin(controller: self, dismissHandle: { [weak self] (result) in
            self?.updateUI()
        })
    }
    //去评分
    func review() {
        if #available(iOS 10.3, *) {
            if SKStoreReviewController.responds(to: #selector(SKStoreReviewController.requestReview)) {
                UIApplication.shared.keyWindow?.endEditing(true)
                SKStoreReviewController.requestReview()
            }
        } else {
            // Fallback on earlier versions
//            NSString  * nsStringToOpen = [NSString  stringWithFormat: @"itms-apps://itunes.apple.com/app/id%@?action=write-review",@"AppID"];//替换为对应的APPID
            let stringToOpen = "itms-apps://itunes.apple.com/app/id\(Config.default.appId)?action=write-review"
            UIApplication.shared.openURL(URL.init(string: stringToOpen)!)
        }
    }

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
